package com.ea.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.framework.util.Assert;
import com.ea.api.param.LoginParam;
import com.ea.api.vo.UserInfoVO;
import com.ea.repository.entity.SysUser;
import com.ea.repository.mapper.SysUserMapper;
import com.ea.service.ISysUserService;
import com.ea.util.RedisUtils;
import com.ea.util.TokenUtil;
import com.ea.util.session.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 系统用户表 服务实现类
 *
 * @author Xiong Cai
 * @since 2024-11-11 11:01
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public SysUser queryById(String id) {
        return null;
    }

    @Override
    public Page<SysUser> queryByPage(SysUser sysUser, PageRequest pageRequest) {
        return null;
    }

    @Override
    public SysUser insert(SysUser sysUser) {
        return null;
    }

    @Override
    public SysUser update(SysUser sysUser) {
        return null;
    }

    @Override
    public boolean deleteById(String id) {
        return false;
    }

    @Override
    public UserInfoVO login(LoginParam param) {
        UserInfoVO userInfoVO = new UserInfoVO();

        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysUser::getLoginName, param.getUsername())
                .or().eq(SysUser::getUserMobile, param.getUsername());

        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        Assert.isNullThrow(sysUser, "用户不存在");
        /*密码16进制转字符串*/
        //String decodedStr = HexUtil.decodeHexStr(param.getPassword());
        /*SHA256加密*/
        String passwordEncrypt = DigestUtil.sha256Hex(param.getPassword() + "_" + sysUser.getSalt());
        Assert.isTrueThrow(!passwordEncrypt.equals(sysUser.getPassword()), "密码错误");
        BeanUtil.copyProperties(sysUser, userInfoVO);
        /**用户token生成**/
        String token = TokenUtil.createToken(sysUser.getId().toString(), (byte) 0);
        userInfoVO.setToken(token);
        /*初始化权限菜单等数据*/

        SessionUtil.putAppUser(userInfoVO);
        /**将用户信息放入到Redis中**/
        redisUtils.set(token, userInfoVO, 60L, TimeUnit.MINUTES);
        return userInfoVO;
    }
}
